package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utilis.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
//@Aspect
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

//    @Autowired
//    private HttpServletRequest request;//获取请求对象
    @Around("execution(* com.itheima.service.*Service.*(..)) && @annotation(com.itheima.anno.LogOperation)")
    public Object recordOperationLog(ProceedingJoinPoint joinPoint/*连接点目标方法，封装了目标方法的运行信息*/) throws Throwable {
        //记录操作日志，收集操作日志信息，添加到操作日志数据表中
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        //1、定义操作日志对象，收集操作日志信息
        OperateLog  operateLog = new OperateLog();
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setCostTime(costTime);//获取目标方法耗时
        operateLog.setReturnValue(result+"");//获取目标方法返回值

        operateLog.setClassName(joinPoint.getTarget().getClass().getName());//获取目标类名
        operateLog.setMethodName(joinPoint.getSignature().getName());//获取目标方法名
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));//获取目标方法参数

        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        //调用操作日志的持久层接口，将操作日志数据保存到数据库中
        operateLogMapper.insert(operateLog);
        return result;
    }
}
